package code.lucamarrocco.classresolver;


public class ClassResolver {

	private String className(Class resolvingClass, Class forClass) {
		String forClassName = forClass.getName();
		String resolvingName = resolvingClass.getSimpleName();
		return new StringBuffer().append(forClassName).append(resolvingName).toString();
	}

	private Class loadClass(Class forClass, String name) {
		try {
			return forClass.getClassLoader().loadClass(name);
		} catch (ClassNotFoundException e) {
			return null;
		}
	}

	private Object newInstance(Class resolvingClass, Class forClass) {
		if (forClass == Object.class) return null;
		return newInstance(resolvingClass, forClass, className(resolvingClass, forClass));
	}

	private Object newInstance(Class resolvingClass, Class forClass, String name) {
		Class loadedClass = loadClass(forClass, name);
		if (loadedClass != null) return newInstance(loadedClass);
		return newInstance(resolvingClass, forClass.getSuperclass());
	}

	private Object newInstance(Class resolvingClass) {
		try {
			return resolvingClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public Object resolveClassFor(Class resolvingClass, Object object) {
		return newInstance(resolvingClass, object.getClass());
	}

	public ClassResolver() {
	}
}